package com.aube.base.player;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.interact.base.R;
import com.huyn.baseframework.utils.PlayerUtil;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by hill on 10/24.
 */
public class TouchableProgress extends LinearLayout {

    private View mRoot;

    private ImageView mImg;
    private TextView mText;
    private ProgressView mProgress;

    private AtomicBoolean mVisible = new AtomicBoolean(false);

    private int mForegroundColor = Color.WHITE;

    public TouchableProgress(Context context) {
        this(context, null);
    }

    public TouchableProgress(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TouchableProgress(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
        mRoot = LayoutInflater.from(getContext()).inflate(R.layout.aube_intera_layout_progress, this);

        mImg = (ImageView) mRoot.findViewById(R.id.progress_img);
        mText = (TextView) mRoot.findViewById(R.id.progress_txt);
        mProgress = (ProgressView) mRoot.findViewById(R.id.progress_view);

        mForegroundColor = getResources().getColor(R.color.progress_color);
    }

    public void updateProgress(boolean forward, float ratio, long current, long duration) {
        show();

        mImg.setImageResource(forward ? R.drawable.icon_forward : R.drawable.icon_backward);
        String strDuration = PlayerUtil.millsecondsToMinutes(duration);
        String strTarget = PlayerUtil.millsecondsToMinutes((long) (duration*ratio));

        String str = strTarget + " / " + strDuration;
        SpannableStringBuilder span = new SpannableStringBuilder(str);
        span.setSpan(new ForegroundColorSpan(mForegroundColor), 0, strTarget.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        mText.setText(span);

        mProgress.updateProgress(ratio, (float) (current*1.0/duration));
    }

    private void show() {
        if(mVisible.get())
            return;
        mVisible.set(true);

        ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0, 1);
        anim.setDuration(200);
        anim.start();
    }

    public void hide() {
        mVisible.set(false);
        ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1, 0);
        anim.setDuration(200);
        anim.start();
    }

}
